Completed
Push — master ( 502c8a...95462b )
by Alejandro
14s
created

server.js ➔ ... ➔ ???   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 1
ccs 1
cts 1
cp 1
crap 1
rs 10
1
import { handleActions } from 'redux-actions';
2
import { pipe, isEmpty, assoc, map, prop } from 'ramda';
3
import { v4 as uuid } from 'uuid';
4
import { homepage } from '../../../package.json';
5
6
/* eslint-disable padding-line-between-statements */
7 1
export const FETCH_SERVERS_START = 'shlink/servers/FETCH_SERVERS_START';
8 1
export const FETCH_SERVERS = 'shlink/servers/FETCH_SERVERS';
9
/* eslint-enable padding-line-between-statements */
10
11 1
const initialState = {
12
  list: {},
13
  loading: false,
14
};
15
16 2
const assocId = (server) => assoc('id', server.id || uuid(), server);
17
18
export default handleActions({
19
  [FETCH_SERVERS_START]: (state) => ({ ...state, loading: true }),
20 1
  [FETCH_SERVERS]: (state, { list }) => ({ list, loading: false }),
21
}, initialState);
22
23 2
export const listServers = ({ listServers, createServers }, { get }) => () => async (dispatch) => {
24 2
  dispatch({ type: FETCH_SERVERS_START });
25 2
  const localList = listServers();
26
27 2
  if (!isEmpty(localList)) {
28 1
    dispatch({ type: FETCH_SERVERS, list: localList });
29
30 1
    return;
31
  }
32
33
  // If local list is empty, try to fetch it remotely and calculate IDs for every server
34 1
  const remoteList = await get(`${homepage}/servers.json`)
35
    .then(prop('data'))
36
    .then(map(assocId))
37
    .catch(() => []);
38
39 1
  createServers(remoteList);
40 1
  dispatch({ type: FETCH_SERVERS, list: remoteList.reduce((map, server) => ({ ...map, [server.id]: server }), {}) });
41
};
42
43 1
export const createServer = ({ createServer }, listServersAction) => pipe(createServer, listServersAction);
44
45 1
export const deleteServer = ({ deleteServer }, listServersAction) => pipe(deleteServer, listServersAction);
46
47 1
export const createServers = ({ createServers }, listServersAction) => pipe(
48
  map(assocId),
49
  createServers,
50
  listServersAction
51
);
52